package net.yihang.miaosha.controller.exception;

import net.yihang.miaosha.controller.result.CodeMsg;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(AccessException.class)
    public String accessException(AccessException e) {
        return "redirect:/login/toLogin";
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseEntity<CodeMsg> bindException(BindException e) {

        List<ObjectError> errors = e.getAllErrors();
        ObjectError error = errors.get(0);
        String msg = error.getDefaultMessage();
        return ResponseEntity.badRequest().body(CodeMsg.MOBILE_PATTERN_ERROR);

    }
}
